<template>
  <div class="app-container1" style="padding: 20px; width: 1100px">
   <!-- <div @click="config.pageSize += 1">加一</div>-->
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="商户编码" v-model="listQuery.code">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="商户名称" v-model="listQuery.name">
      </el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
     <!-- <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <el-table  stripe  :key='tableKey'
               :data = "showListData"

               v-loading="listLoading" border fit highlight-current-row
              style="width: 100%; height:100%; margin-top: 20px">
      <!--<el-table-column align="center" label="序号" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>-->
      <el-table-column width="150px"  prop="tenantCode" align="center" label="商户编码">
       <!-- <template slot-scope="scope">
          <span>{{scope.tenantCode }}</span>
        </template>-->
      </el-table-column>
      <el-table-column min-width="150px" prop="tenantName" label="商户名称">
        <!--<template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.title}}</span>
          <el-tag>{{scope.row.type | typeFilter}}</el-tag>
        </template>-->
      </el-table-column>
      <el-table-column width="110px" align="center" prop="tenantAddress" label="商户地址">
       <!-- <template slot-scope="scope">
          <span>{{scope.row.author}}</span>
        </template>-->
      </el-table-column>
      <el-table-column width="110px"  prop="tenantType" align="center" label="业务类型">
      <!--  <template slot-scope="scope">
          <span style='color:red;'>{{scope.row.reviewer}}</span>
        </template>-->
      </el-table-column>
      <el-table-column width="80px" prop="open" label="是否启用">
       <!-- <template slot-scope="scope">
          <svg-icon v-for="n in +scope.row.importance" icon-class="star" class="meta-item__icon" :key="n"></svg-icon>
        </template>-->
      </el-table-column>
      <el-table-column align="center" prop="set" label="系统内置" width="95">
       <!-- <template slot-scope="scope">
          <span v-if="scope.row.pageviews" class="link-type" @click='handleFetchPv(scope.row.pageviews)'>{{scope.row.pageviews}}</span>
          <span v-else>0</span>
        </template>-->
      </el-table-column>

      <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button  size="mini" type="danger" @click="handleModifyStatus(scope.row,'deleted')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" style="margin-top: 20px" v-show="!isSearch">
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :page-size="config.pageSize"
                     :current-page="config.currentPage"
                     layout=" prev, pager, next, jumper"
                     :total="fakeList.length">
      </el-pagination>
    </div>

    <div class="pagination-container" style="margin-top: 20px" v-show="isSearch">
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :page-size="config.pageSize"
                     :current-page="config.currentPage"
                     layout=" prev, pager, next, jumper"
                     :total="fakeListSearch.length">
      </el-pagination>
    </div>


    <el-dialog title="编辑-商户信息" :visible.sync="dialogFormVisible" style="margin-top: 150px">
      <el-form  ref="dataForm" :model="temp" label-position="left" label-width="70px"
                style='width: 400px; margin-left:50px;'>
        <el-form-item label="商户编码" prop="type">
          <el-input v-model="temp.tenantCode"></el-input>
        </el-form-item>
        <el-form-item label="商户名称" prop="timestamp">
          <el-input v-model="temp.tenantName"></el-input>
        </el-form-item>
        <el-form-item label="商户地址" prop="title">
          <el-input v-model="temp.tenantAddress"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createData">确定</el-button>
       <!-- <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>-->
      </div>
    </el-dialog>

    <!--<el-dialog title="Reading statistics" :visible.sync="dialogPvVisible">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"> </el-table-column>
        <el-table-column prop="pv" label="Pv"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{$t('table.confirm')}}</el-button>
      </span>
    </el-dialog>-->

  </div>
</template>

<script>
 // import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
 // import waves from '@/directive/waves' // 水波纹指令
 // import { parseTime } from '@/utils'
import {dataList} from './data.json'
  const calendarTypeOptions = [
    { key: 'CN', display_name: 'China' },
    { key: 'US', display_name: 'USA' },
    { key: 'JP', display_name: 'Japan' },
    { key: 'EU', display_name: 'Eurozone' }
  ]

  // arr to obj ,such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'complexTable',
   /* directives: {
      waves
    },*/
    data() {
      return {
        config:{
          pageSize:7,
          currentPage:1
        },
        listQuery:{
          code:'',
          name:''
        },
        showListData:[],
        tableKey: 0,
        list: null,
        fakeList:[],
        fakeListSearch:[],
        isSearch:false,
        total: null,
        listLoading: false,  //初始为true 获取接口数据后转为false  ，假数据直接为false
        /*listQuery: {
          page: 1,
          limit: 5,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },*/
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          tenantCode: '',
          tenantName: '',
          tenantAddress: '',

        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    created() {
      this.initDataList()
      this.sliceData()
    },
    watch:{
        //当搜索信息为空时，显示所有列表
      listQuery:{      //深度监听，可监听到对象、数组的变化
        handler(newVal, oldVal){
          if(newVal.code =='' && newVal.name == ''){
              this.isSearch = false
              console.log('code变化')
           // this.config.currentPage = 1
          //  this.handleCurrentChange(1)
            this.sliceData()
          }
        },
        deep:true
      },
    /*  config:{
        handler(newVal, oldVal){
          if(newVal.currentPage =='' ){
            console.log('currentPage变化')
            this.config.currentPage = 1
           // this.sliceData()
          }
        },
        deep:true
      }*/
    },
    computed:{
      code(){
        return this.listQuery.code
      },
     /* currentPage(){
        return this.config.currentPage
      }*/
    },
    methods: {

      sliceData(){
          if(this.listQuery.code == '' &&this.listQuery.name==''){ //无查询时
            this.showListData = this.fakeList.slice((this.config.currentPage-1)*this.config.pageSize,this.config.currentPage*this.config.pageSize)
          }else { //有查询时
            this.showListData = this.fakeListSearch.slice((this.config.currentPage-1)*this.config.pageSize,this.config.currentPage*this.config.pageSize)
          }
      },
      initDataList(){
          this.fakeList = dataList
          this.fakeListSearch = dataList

      },
     /* getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },*/
      getList() {
          let tempList = this.fakeList
        //商户编码查询
          if(this.listQuery.code && this.listQuery.name === ''){
            //  console.log('getList的code')
           // console.log(this.listQuery.code,'this.listQuery.code')
            this.fakeListSearch = tempList.filter( (item) =>{
              return item.tenantCode == this.listQuery.code
            })
          }
        let limitNameList = []
          //商户名称查询 和 商户名称查询
          if(this.listQuery.name){
              for(let i=0;i<tempList.length;i++){
                if(tempList[i].tenantName.indexOf(this.listQuery.name) !== -1){
                  limitNameList.push(tempList[i])
                }
              }
            this.fakeListSearch = limitNameList
            if(this.listQuery.code){
              //  console.log('getList的code')
              // console.log(this.listQuery.code,'this.listQuery.code')
              this.fakeListSearch = tempList.filter( (item) =>{
                return item.tenantCode == this.listQuery.code
              })
            }
          }






          // Just to simulate the time 1of the request
      },
      handleFilter() {
        this.isSearch = true
        this.config.currentPage = 1
        this.getList()
        this.sliceData()  //可以重新给搜索的总数组赋值
      },
      handleSizeChange(val) {
          console.log('handleSizeChange',val)
        this.config.currentPage = val
        this.getList()
      },
     /* handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },*/

      handleCurrentChange(val) {
        console.log('handleCurrentChange',val)
        this.config.currentPage = val
        this.sliceData()
      },

      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogFormVisible = true
      /*  this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })*/
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      },
    /*  handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },*/
     /* handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },*/
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
